import * as path from 'node:path';
import * as vscode from 'vscode';
import * as configuration from '../configuration';
import { Helper } from '../helper';
import { log } from '../helper/outputChannel';
import { outputFile } from '../helper/outputFile';
import { Memory } from '../memory';
import { addUser } from './addUser';
import { fetchApiList } from './fetchApiList';
import { OpenApiDoc } from './openApi';
import { ensureOutputDir } from './selectOutputDir';
import { ensureTemplateFile } from './selectTemplateFile';
import { fetchDocDetail } from '../api/fetchDocDetail';
import { TornaDocDetail, TornaDocItem } from '../types/type';


export async function genApiTsFile(arg0: any) {
  log.show(true);
  const docItem = await OpenApiDoc.getDocItemFormAny(arg0);
  if (!docItem) { return; }
  return await genApiTsfileByMemoryDoc(docItem);
}

export async function genApiTsFileAndOpen(arg0: any) {
  return await genApiTsFile(arg0).then((result) => {
    const uri = vscode.Uri.file(result?.filePath!);
    return vscode.commands.executeCommand('vscode.open', uri);
  });
}

export interface GenApiTsfileByDocDetailInits {
  detail: TornaDocDetail;
  visitor: Memory.IUser;
}

export async function genApiTsfileByDocDetail(inits: GenApiTsfileByDocDetailInits) {
  const { detail, visitor } = inits;
  const outputDirPath = await ensureOutputDir(detail).catch(e => log.error(e));
  if (!outputDirPath) { return; }
  const templateFilePath = await ensureTemplateFile(detail).catch(e => log.error(e));
  if (!templateFilePath) { return; }
  const workspace = await Helper.workspace().catch(e => { vscode.window.showErrorMessage(e); });
  if (!workspace) { return; }
  const workspacePath = Helper.fsPath(workspace.uri);
  return await outputFile({
    outputDirPath: path.join(workspacePath, outputDirPath),
    templateFilePath: path.join(workspacePath, templateFilePath),
    detail,
    visitor
  });
}

export async function genApiTsfileByMemoryDoc(doc: Memory.IDoc) {
  const users = await configuration.getUsers();
  if (!users.length) {
    log.warn('请先添加Torna用户');
    log.show();
    await addUser();
  }

  let docList = Memory.fullDocList.filter(v => v.url);
  if (!docList.length) {
    await fetchApiList();
  }

  docList = Memory.fullDocList.filter(v => v.url);
  if (!docList.length) {
    log.warn('接口文档列表为空');
    log.show();
    return;
  }
  const detail = await fetchDocDetail(
    doc.visitor.url + '/doc/view/detail',
    { authorization: doc.visitor.token },
    { id: doc.id },
  );
  return await genApiTsfileByDocDetail({
    detail, visitor: doc.visitor
  });
}